package com.hboxs.asl.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.springframework.http.HttpStatus;

import javax.swing.*;
import java.io.*;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by study on 6/24/2015.
 */
public class HttpSender {
    public HttpSender() {
    }

    public static String send(String uri, String account, String pswd, String mobiles, String content, boolean needstatus, String product, String extno) throws Exception {

        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod();

        try {
            URI base = new URI(uri, false);
            method.setURI(new URI(base, "HttpSendSM", false));
            method.setQueryString(new NameValuePair[]{new NameValuePair("account", account), new NameValuePair("pswd", pswd), new NameValuePair("mobile", mobiles), new NameValuePair("needstatus", String.valueOf(needstatus)), new NameValuePair("msg", content), new NameValuePair("product", product), new NameValuePair("extno", extno)});
            int result = client.executeMethod(method);
            if (result != 200) {
                throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
            } else {
                InputStream in = method.getResponseBodyAsStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                boolean len = false;

                int len1;
                while ((len1 = in.read(buffer)) != -1) {
                    baos.write(buffer, 0, len1);
                }

                String var17 = URLDecoder.decode(baos.toString(), "UTF-8");
                return var17;
            }
        } finally {
            method.releaseConnection();
        }
    }

    public static String batchSend(String uri, String account, String pswd, String mobiles, String content, boolean needstatus, String product, String extno) throws Exception {
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod();

        try {
            URI base = new URI(uri, false);
            method.setURI(new URI(base, "HttpBatchSendSM", false));
            method.setQueryString(new NameValuePair[]{new NameValuePair("account", account), new NameValuePair("pswd", pswd), new NameValuePair("mobile", mobiles), new NameValuePair("needstatus", String.valueOf(needstatus)), new NameValuePair("msg", content), new NameValuePair("product", product), new NameValuePair("extno", extno)});
            int result = client.executeMethod(method);
            if (result != 200) {
                throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
            } else {
                InputStream in = method.getResponseBodyAsStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                boolean len = false;

                int len1;
                while ((len1 = in.read(buffer)) != -1) {
                    baos.write(buffer, 0, len1);
                }

                String var17 = URLDecoder.decode(baos.toString(), "UTF-8");
                return var17;
            }
        } finally {
            method.releaseConnection();
        }
    }

    /**
     * post请求
     *
     * @param url            url地址
     * @param jsonParam      参数
     * @param noNeedResponse 不需要返回结果
     * @return
     */
    public static JSONObject httpPost(String url, List<BasicNameValuePair> jsonParam, boolean noNeedResponse) {
        //post请求返回结果
        DefaultHttpClient httpClient = new DefaultHttpClient();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                method.setEntity(new UrlEncodedFormEntity(jsonParam));
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发送成功，并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }
                    /**把json字符串转换成json对象**/
                    jsonResult = new JSONObject(str);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonResult;
    }

    /**
     * get请求
     *
     * @param url url地址
     * @return
     */
    public static JSONObject getHisData(String url) {
        DefaultHttpClient client = new DefaultHttpClient();
//        HttpPost post = new HttpPost(url);
        HttpGet get = new HttpGet(url);
        JSONObject response = null;
        try {
            HttpResponse res = client.execute(get);
            if (res.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                HttpEntity entity = res.getEntity();
                String charset = EntityUtils.getContentCharSet(entity);
                response = new JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(), charset)));
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return response;
    }

    public static void main(String[] args) {
        List<BasicNameValuePair> nvps = new ArrayList<>();
        String client = "third";
        String appid = "72545354575996016";
        String member_name = "15600000000";
        String password = "a123456";
        String appSecret = "cfc2c59b7d367485a1a21c573d7118be";
        Long t = System.currentTimeMillis()/1000;

        nvps.add(new BasicNameValuePair("client", client));
        nvps.add(new BasicNameValuePair("appid", appid));
        nvps.add(new BasicNameValuePair("member_name", member_name));
        nvps.add(new BasicNameValuePair("password", password));
        nvps.add(new BasicNameValuePair("t", t.toString()));
        System.out.println(t.toString());
        String postData = client + appid + member_name + password + t.toString();
        String token = DigestUtils.md5Hex(DigestUtils.md5Hex(t.toString() + appid + postData + appSecret));
        nvps.add(new BasicNameValuePair("token", token));

        JSONObject result = httpPost("http://120.25.212.243/p_center/open/index.php?act=auth", nvps, false);
        System.out.println(result);
        System.out.println(((JSONObject)result.get("data")).get("auth_key"));



    }
}
